// 患者问诊聊天页面组件



import React, { useState, useRef, useEffect } from 'react';
import { NavBar, Button, Field, Image, Toast, Popup } from 'react-vant';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import axios from '../../request/axios';
import data from '@emoji-mart/data';
import Picker from '@emoji-mart/react';
import { SmileO } from '@react-vant/icons';
import './chat.less';

// 常用表情列表
const QUICK_EMOJIS = [
  '😊', '😂', '😍', '🤔', '👍', '❤️', '🙏', '😷',
  '😭', '😡', '😴', '🤗', '🤢', '🤧', '🤒', '😇'
];

interface Message {
  id: string;
  content: string;
  type: 'text' | 'image';
  sender: 'patient' | 'doctor';
  timestamp: string;
}

interface RTKData {
  latitude: string;
  longitude: string;
  accuracy: string;
  timestamp: number;
}

const Chat: React.FC = () => {
  const navigate = useNavigate();
  const { id } = useParams<{ id: string }>();
  const [searchParams] = useSearchParams();
  const doctorId = searchParams.get('doctorId');
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputValue, setInputValue] = useState('');
  const [loading, setLoading] = useState(false);
  const [showEmojiPicker, setShowEmojiPicker] = useState(false);
  const [showQuickEmojis, setShowQuickEmojis] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // 获取RTK数据
  const getRTKData = (): RTKData => {
    return {
      latitude: localStorage.getItem('latitude') || '0',
      longitude: localStorage.getItem('longitude') || '0',
      accuracy: localStorage.getItem('accuracy') || '0',
      timestamp: new Date().getTime()
    };
  };

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  // 获取聊天记录
  useEffect(() => {
    const fetchChatHistory = async () => {
      try {
        setLoading(true);
        // TODO: 调用实际的聊天记录接口
        const mockMessages: Message[] = [
          {
            id: '1',
            content: '医生您好，我最近感觉不太舒服',
            type: 'text',
            sender: 'patient',
            timestamp: '2024-03-10 10:00:00'
          },
          {
            id: '2',
            content: '您好，请详细描述一下您的症状',
            type: 'text',
            sender: 'doctor',
            timestamp: '2024-03-10 10:01:00'
          }
        ];
        setMessages(mockMessages);
      } catch (error) {
        console.error('获取聊天记录失败:', error);
        Toast.fail('获取聊天记录失败');
      } finally {
        setLoading(false);
      }
    };

    if (id) {
      fetchChatHistory();
    }
  }, [id]);

  const handleSend = async () => {
    if (!inputValue.trim()) return;

    const newMessage: Message = {
      id: Date.now().toString(),
      content: inputValue,
      type: 'text',
      sender: 'patient',
      timestamp: new Date().toISOString()
    };

    setMessages(prev => [...prev, newMessage]);
    setInputValue('');

    try {
      // 获取用户信息
      const userInfoStr = localStorage.getItem('userInfo');
      if (!userInfoStr) {
        Toast.fail('请先登录');
        navigate('/patient-login');
        return;
      }

      const userInfo = JSON.parse(userInfoStr);
      const { userId, sessionId } = userInfo;

      // 构建请求参数
      const requestData = {
        inquiryId: parseInt(id || '0', 10),
        content: inputValue,
        type: 1,
        doctorId: parseInt(doctorId || '0', 10),
        rtk: getRTKData() // 添加RTK数据
      };

      console.log('Request Data:', requestData); // 调试日志

      const response = await axios({
        url: '/health/user/inquiry/verify/v1/pushMessage',
        method: 'post',
        headers: {
          'userId': userId.toString(),
          'sessionId': sessionId,
          'Content-Type': 'application/json'
        },
        data: requestData
      });

      if (response.data.status !== '0000') {
        throw new Error(response.data.message || '发送消息失败');
      }

      // 发送成功后，可以在这里添加极光推送的逻辑
      // TODO: 实现极光推送

    } catch (error: any) {
      console.error('发送消息失败:', error);
      if (error.response) {
        console.error('Error Response:', error.response.data);
      }
      Toast.fail(error.message || '发送消息失败');
      // 如果发送失败，从消息列表中移除该消息
      setMessages(prev => prev.filter(msg => msg.id !== newMessage.id));
    }
  };

  const handleEmojiSelect = (emoji: any) => {
    setInputValue(prev => prev + emoji.native);
    setShowEmojiPicker(false);
  };

  const handleQuickEmojiClick = (emoji: string) => {
    setInputValue(prev => prev + emoji);
  };

  const formatTime = (timestamp: string) => {
    const date = new Date(timestamp);
    return date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  return (
    <div className="chat-page">
      <NavBar
        title="问诊详情"
        leftText="返回"
        onClickLeft={() => navigate(-1)}
        rightText={
          <Button
            type="danger"
            size="small"
            onClick={() => navigate('/inquiry/end/' + id)}
          >
            结束问诊
          </Button>
        }
      />

      <div className="chat-container">
        <div className="messages">
          {messages.map((message) => (
            <div
              key={message.id}
              className={`message-item ${message.sender === 'patient' ? 'sent' : 'received'}`}
            >
              <div className="message-content">
                {message.type === 'text' ? (
                  <div className="text">{message.content}</div>
                ) : (
                  <Image src={message.content} width="120" height="120" />
                )}
                <div className="time">{formatTime(message.timestamp)}</div>
              </div>
            </div>
          ))}
          <div ref={messagesEndRef} />
        </div>

        <div className="quick-emojis" style={{ display: showQuickEmojis ? 'flex' : 'none' }}>
          {QUICK_EMOJIS.map((emoji, index) => (
            <div
              key={index}
              className="quick-emoji-item"
              onClick={() => handleQuickEmojiClick(emoji)}
            >
              {emoji}
            </div>
          ))}
        </div>

        <div className="input-area">
          <Field
            value={inputValue}
            onChange={setInputValue}
            placeholder="请输入消息..."
            maxLength={500}
            border={false}
            leftIcon={
              <SmileO
                fontSize={24}
                onClick={() => setShowQuickEmojis(!showQuickEmojis)}
                style={{ cursor: 'pointer' }}
              />
            }
            rightIcon={
              <Button
                type="primary"
                size="small"
                onClick={handleSend}
                disabled={!inputValue.trim()}
              >
                发送
              </Button>
            }
          />
        </div>
      </div>

      <Popup
        visible={showEmojiPicker}
        position="bottom"
        onClose={() => setShowEmojiPicker(false)}
        style={{ height: '50%' }}
      >
        <div style={{ height: '100%', overflow: 'hidden' }}>
          <Picker
            data={data}
            onEmojiSelect={handleEmojiSelect}
            theme="light"
            locale="zh"
            previewPosition="none"
            skinTonePosition="none"
          />
        </div>
      </Popup>
    </div>
  );
};

export default Chat; 